package com.plugin.uniapp.utils;

import android.os.Handler;
import android.os.Looper;

import androidx.annotation.NonNull;

import com.plugin.uniapp.Config;

import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpHelper {
    private static final OkHttpClient client = new OkHttpClient();
    private static final Handler mainHandler = new Handler(Looper.getMainLooper());

    public interface Callback {
        void onSuccess(String res);
    }

    public static String getSync(String url) {
        String token = Config.UserToken;
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", "Bearer " + token)
                .get()
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.code() != 200) {
                error("同步Get响应[" + url + "]code：" + response.code());
                return null;
            }
            if (response.body() == null) {
                error("同步Get响应[" + url + "]response.body()=null");
                return null;
            }
            return response.body().string();
        } catch (IOException e) {
            error("同步Get请求失败[" + url + "]：" + e.getMessage());
            return null;
        }
    }

    public static void getAsync(String url, Callback callback) {
        String token = Config.UserToken;
        Request request = new Request.Builder().url(url).addHeader("Authorization", "Bearer " + token).get().build();

        client.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                error("Get请求失败[" + url + "]：" + e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                try {
                    String responseContent;
                    if (response.code() == 200) {
                        if (response.body() != null) {
                            responseContent = response.body().string();
                        } else {
                            error("异步Get响应失败[" + url + "]response.body()=null");
                            responseContent = null;
                        }
                    } else {
                        error("异步Get响应失败[" + url + "]code：" + response);
                        responseContent = null;
                    }
                    mainHandler.post(() -> {
                        callback.onSuccess(responseContent);
                    });
                } catch (IOException e) {
                    error("Get响应报错[" + url + "]：" + e.getMessage());
                }
            }
        });
    }

    public static String postSync(String url, JSONObject data) {
        RequestBody body = RequestBody.create(data.toString(), MediaType.parse("application/json; charset=utf-8"));
        String token = Config.UserToken;
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", "Bearer " + token)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (response.code() != 200) {
                error("同步Post响应[" + url + "]code：" + response.code());
                return null;
            }
            if (response.body() == null) {
                error("同步Post响应[" + url + "]response.body()=null");
                return null;
            }
            return response.body().string();
        } catch (IOException e) {
            error("同步Post请求失败[" + url + "]：" + e.getMessage());
            return null;
        }
    }

    public static void postAsync(String url, JSONObject data, Callback callback) {
        RequestBody body = RequestBody.create(data.toString(), MediaType.parse("application/json; charset=utf-8"));
        String token = Config.UserToken;
        Request request = new Request.Builder().url(url).addHeader("Authorization", "Bearer " + token).post(body).build();
        client.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                error("Post请求失败[" + url + "]：" + e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                try {
                    String responseContent;
                    if (response.code() == 200) {
                        if (response.body() != null) {
                            responseContent = response.body().string();
                        } else {
                            error("异步Post响应失败[" + url + "]response.body()=null");
                            responseContent = null;
                        }
                    } else {
                        error("异步Post响应失败[" + url + "]code：" + response);
                        responseContent = null;
                    }
                    mainHandler.post(() -> {
                        callback.onSuccess(responseContent);
                    });
                } catch (IOException e) {
                    error("Post响应报错[" + url + "]：" + e.getMessage());
                }
            }
        });
    }

    private static void log(String msg) {
        Logger.log(msg, HttpHelper.class, false);
    }

    private static void error(String msg) {
        Logger.error(msg, HttpHelper.class, false);
    }
}